package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.User;
import model.YourCart;

import dto.DataManager;

/**
 * Servlet implementation class UpdateCart
 */
@WebServlet("/UpdateCart")
public class AddCart extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		
        String username =(String) session.getAttribute("username");
        DataManager dataManager = new DataManager();
       
        User user = username ==null ? null : dataManager.getUserWithUserName(username);
        int productId = request.getParameter("productId")==null ? -1 : Integer.parseInt(request.getParameter("productId"));
          request.setCharacterEncoding("UTF-8");  
       response.setContentType("text/html;charset=UTF-8");
       response.setCharacterEncoding("UTF-8");
       PrintWriter out = response.getWriter();
        
        if(productId != -1&& user!=null)
        {
        	if(dataManager.checkCartProduct(productId, user.getUserId()))
        	{
	        	YourCart y = new YourCart();
	        	y.setUserId(user.getUserId());
	        	y.setProductId(productId);
	        	y.setDateTimeExport(new Date().toString());
	        	dataManager.insertYourCart(y);
	        	out.print("<p>Thêm thành công vào  ");
             	out.println(" <a href=\"yourCart.jsp\">giỏ hàng</a><br></p>");
	        	
        	}
        	else
        	{
        		out.print("<p>Đã tồn tại trong  <a  href=\"yourCart.jsp\">giỏ hàng</a></p>");
        	}
        }
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
